package com.steakliu.sun.common.thread;

import java.util.concurrent.*;

/**
 * 功能说明： 客户端并发线程池
 * <p>
 * Original @Author: steakliu-刘牌, 2023-02-03  11:01
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class ClientConcurrentThreadPool {

    private static ExecutorService executorService;

    private static volatile ClientConcurrentThreadPool clientConcurrentThreadPool;

    public ClientConcurrentThreadPool(int concurrentCorePoolSize, int concurrentMaximumPoolSize) {
        if (concurrentCorePoolSize <= 0) {
            concurrentCorePoolSize = 2;
        }
        if (concurrentMaximumPoolSize <= 0) {
            concurrentMaximumPoolSize = Runtime.getRuntime().availableProcessors();
        }
        executorService = new ThreadPoolExecutor(concurrentCorePoolSize,
                concurrentMaximumPoolSize,
                10000,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(10000));
    }

    public static ClientConcurrentThreadPool getInstance(int concurrentCorePoolSize, int concurrentMaximumPoolSize) {
        if (null == clientConcurrentThreadPool) {
            synchronized (ClientConcurrentThreadPool.class) {
                if (null == clientConcurrentThreadPool) {
                    clientConcurrentThreadPool = new ClientConcurrentThreadPool(concurrentCorePoolSize, concurrentMaximumPoolSize);
                }
            }
        }
        return clientConcurrentThreadPool;
    }


    public void submit(Runnable runnable) {
        executorService.submit(runnable);
    }

    public <T> T submit(Callable<T> task) {
        Future<T> future = executorService.submit(task);
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void shutdown() {
        executorService.shutdownNow();
    }
}
